const log = require('../../util/log'),
  config = require('../../util/config'),
  logger = require('log4js').getLogger()

async function loginJd(obj) {
  const {
    Network,
    Page,
    DOM,
    Runtime,
    Emulation
  } = this.client;
  obj = obj || {}
  obj.times = (obj.times || 0) + 1
  if (obj.times > config.chromeMaxTimes) {
    return new Promise((resolve, reject) => {
      reject('系统错误')
    })
  }
  if (obj.step !== 0) {
    logger.debug('[' + __filename + ':' + __line + ']', 'logining jd')
    obj.step = 0
  }
  try {
    await Page.navigate({
      url: 'https://media.jd.com/'
    })
    return new Promise((resolve, reject) => {
      step1.call(this, obj).then(result => {
        this.code = ''
        this.codeRequestId = 0
        this.codeText = ''
        resolve(result)
      }, result => {
        this.code = ''
        this.codeRequestId = 0
        this.codeText = ''
        reject(result)
      })
    })
  } catch (err) {
    log(err)
  }
}

async function step1(obj) {
  const {
    Network,
    Page,
    DOM,
    Runtime,
    Emulation
  } = this.client;
  obj.times++;
  if (obj.times > config.chromeMaxTimes) {
    return new Promise((resolve, reject) => {
      reject('系统错误')
    })
  }
  if (obj.step !== 1) {
    logger.debug('[' + __filename + ':' + __line + ']', 'logining jd step 1')
    obj.step = 1
  }
  try {
    var {
      result
    } = await Runtime.evaluate({
      expression: 'location.href'
    })
    if (result.value == 'https://media.jd.com/') {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2.call(this, obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 2000)
      })
    }
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        this.loginJd(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 2000)
    })
  } catch (err) {
    log(err)
  }
}

async function step2(obj) {
  const {
    Network,
    Page,
    DOM,
    Runtime,
    Emulation
  } = this.client;
  obj.times++;
  if (obj.times > config.chromeMaxTimes) {
    return new Promise((resolve, reject) => {
      reject('超时')
    })
  }
  if (obj.step !== 2) {
    logger.debug('[' + __filename + ':' + __line + ']', 'logining jd step 2')
    obj.step = 2
  }
  try {
    var {
      result
    } = await Runtime.evaluate({
      expression: 'location.href'
    })
    if (result.value != 'https://media.jd.com/') {
      logger.debug('[' + __filename + ':' + __line + ']', '登录成功跳转')
      return new Promise((resolve, reject) => {
        resolve()
      })
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll("#userPin")'
    })
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 1) {
      var {
        result
      } = await Runtime.evaluate({
        expression: 'document.querySelectorAll("#userPin")[0].innerText'
      })
      if (result.value != '') {
        logger.debug('[' + __filename + ':' + __line + ']', '检测到用户名', JSON.stringify(result))
        Page.navigate({
          url: 'https://media.jd.com/index/overview'
        })
        return new Promise((resolve, reject) => {
          resolve()
        })
      }
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll("iframe")'
    })
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2.call(this, obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    if (cnt > 1) {
      return new Promise((resolve, reject) => {
        log('iframe多于1个')
        reject('系统错误')
      })
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#o-authcode")'
    })
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 1) {
      var {
        result
      } = await Runtime.evaluate({
        expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#o-authcode")[0].className'
      })
      if (result.value.indexOf('hide') == -1) {
        if (!this.codeText) {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              step2.call(this, obj).then(result => {
                resolve(result)
              }, result => {
                reject(result)
              })
            }, 1000)
          })
        }
        await Runtime.evaluate({
          expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#authcode")[0].value="' + this.codeText + '"'
        })
      }
      var {
        result
      } = await Runtime.evaluate({
        expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#o-authcode")[0].style.display'
      })
      if (result.value == 'block') {
        if (!this.codeText) {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              step2.call(this, obj).then(result => {
                resolve(result)
              }, result => {
                reject(result)
              })
            }, 1000)
          })
        }
        await Runtime.evaluate({
          expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#authcode")[0].value="' + this.codeText + '"'
        })
      }
    }
    var {
      result
    } = await Runtime.evaluate({
      expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#loginname")'
    })
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          step2.call(this, obj).then(result => {
            resolve(result)
          }, result => {
            reject(result)
          })
        }, 1000)
      })
    }
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#loginname")[0].value="etourly"'
    })
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#nloginpwd")[0].value="yoyo9876"'
    })
    await Runtime.evaluate({
      expression: 'document.querySelectorAll("iframe")[0].contentDocument.querySelectorAll("#paipaiLoginSubmit")[0].click()'
    })
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        step2.call(this, obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
      }, 1000)
    })
  } catch (err) {
    log(err)
    return new Promise((resolve, reject) => {
      reject('系统错误')
    })
  }
}

module.exports = loginJd